<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="email"
        name="email"
        left-icon="manager"
        label="电子邮箱"
        placeholder="电子邮箱"
        :rules="[{ required: true, message: '请填写电子邮箱' }]"
      />
      <van-field
        v-model="sms"
        center
        name="sms"
        left-icon="lock"
        clearable
        label="验证码"
        placeholder="请输入邮箱验证码"
        :rules="[{ required: true, message: '请输入邮箱验证码' }]"
      >
        <template #button>
          <van-tag v-if="isTiemeshow" class="sendcode" type="danger" round
            ><van-count-down
              @finish="isTiemeshow = false"
              :time="1000 * 60"
              style="color: white; font-size: 12px"
              format="重新发送 ss s"
          /></van-tag>
          <van-button
            v-else
            native-type="button"
            @click="sendemail"
            round
            size="small"
            type="danger"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block native-type="submit" type="danger"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      email: "",
      sms: "",
      newsms: "",
      isTiemeshow: false,
    };
  },
  methods: {
    async onSubmit(values) {
      if (this.sms !== this.newsms) {
        this.$toast({
          message: "验证码错误",
          position: "top",
        });
      } else {
        const { data: res } = await this.$http.get("emailLogin", {
          params: { email: this.email },
        });
        console.log(res);
        if (res.status == 202) {
          this.$toast({
            message: "请确认邮箱是否正确",
            position: "top",
          });
        } else {
          this.$store.commit("setUser", res.data);
          this.$router.push({ path: "/myinfo" });
        }
      }
    },
    async sendemail() {
      //发送验证码
      if (this.email == "") {
        this.$toast({
          message: "请输入邮箱",
          position: "top",
        });
      } else {
        this.isTiemeshow = true;
        const { data: res } = await this.$axios.get("mailbox", {
          params: {
            email: this.email,
            content: "您正在进行登录",
            title: "用户登录",
          },
        });
        // console.log(res.code);
        this.newsms = res.code;
      }
    },
  },
};
</script>
<style lang="less" scoped>
.sendcode {
  height: 2rem;
  width: 5.5rem;
  color: white;
}
</style>